package b0.controller;


import b0.bean.ResultInfo;
import b0.entity.User;
import b0.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController()
@RequestMapping("/user")
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(User.class);
    @Autowired
    UserRepository userRepository;

    @GetMapping("/{id}")
    public ResultInfo getUser(@PathVariable("id") Integer id) {
        ResultInfo resultInfo = new ResultInfo();
        User user = userRepository.getOne(id);
        resultInfo.setData(user);
        return resultInfo;
    }


    @PostMapping("/register")
    public ResultInfo registerUser(User user) {
        ResultInfo resultInfo = new ResultInfo();
        if ((user.getUsername() != null)&&(userRepository.getByUsername(user.getUsername())==null)) {
            User save = userRepository.save(user);
            resultInfo.setStatus(200);
            resultInfo.setMsg("成功添加");
            resultInfo.setData(user);
            logger.info(user.getUsername()+"注册成功");

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("添加失败");
            resultInfo.setData(user);
        }
        return resultInfo;
    }

    @PostMapping("/login")
    public ResultInfo loginUser(User user) {
        ResultInfo resultInfo = new ResultInfo();
        User loginuser = userRepository.getByPasswordAndUsername(user.getPassword(), user.getUsername());
        if (loginuser != null) {
            resultInfo.setStatus(200);
            resultInfo.setMsg("登陆成功");
            resultInfo.setData(loginuser);
            logger.info(user.getUsername()+"登陆成功");

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("登陆失败,请检查用户名和密码");
            resultInfo.setData(user);
        }
        return resultInfo;
    }


}
